package vn.ikame.android.boojtran.truyenbua.download;

import java.io.InputStream;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import vn.ikame.android.boojtran.truyenbua.SuperActivity;
import vn.ikame.android.boojtran.truyenbua.logic.CConstant;
import vn.ikame.android.boojtran.truyenbua.object.Item;
import android.os.AsyncTask;

public class ItemListDownload {
	private ItemListDowloadListener listener;
	private SuperActivity context;

	public ItemListDownload(SuperActivity context,
			ItemListDowloadListener listener) {
		this.context = context;
		this.listener = listener;
	}

	public void start(final int start, final int count) {
		try {
			new AsyncTask<Void, Void, ArrayList<Item>>() {
				@Override
				protected void onPreExecute() {
					super.onPreExecute();
					context.showProgress("Đang tải dữ liệu...");
				}

				@Override
				protected ArrayList<Item> doInBackground(Void... params) {
					return getListItem(start, count);
				}

				@Override
				protected void onPostExecute(ArrayList<Item> result) {
					listener.onDownloadFinish(result, start, count);
					context.dismissProgress();
					super.onPostExecute(result);
				}
			}.execute();
		} catch (Exception e) {
			listener.onDownloadError(start, count);
			e.printStackTrace();
		}
	}

	private ArrayList<Item> getListItem(int start, int count) {
		String url = CConstant.SVR_LINK + "&start=" + start + "&count=" + count;
		// Log.d("TAG", "" + url);
		URL myURL;
		ArrayList<Item> response = new ArrayList<Item>();
		try {
			myURL = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) myURL.openConnection();
			conn.setConnectTimeout(CConstant.TIME_OUT);
			conn.setReadTimeout(CConstant.TIME_OUT);
			InputStream is = conn.getInputStream();
			// Log.i("TAG", "inputstream url " + is.available());
			Document document = parse(is);
			Element root = document.getRootElement();
			for (Iterator<Element> i = root.elementIterator(); i.hasNext();) {
				Element data = (Element) i.next();
				if (data.getQualifiedName().equalsIgnoreCase(
						CConstant.TAG_TOTAL)) {
					try {
						SuperActivity.totalItem = Integer.parseInt(data
								.getText());
						System.out.println("TAG: total= "
								+ SuperActivity.totalItem);
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
				Iterator<Element> itrc = data.elementIterator();
				Item item = new Item();
				while (itrc.hasNext()) {
					Element child = (Element) itrc.next();
					if (child.getQualifiedName().equalsIgnoreCase(
							CConstant.TAG_ID)) {
						try {
							item.setId(Integer.parseInt(child.getText()));
							// System.out.println("TAG: id= " +
							// child.getText());
						} catch (Exception e) {
							item.setId(-1);
							e.printStackTrace();
						}
					}
					if (child.getQualifiedName().equalsIgnoreCase(
							CConstant.TAG_TITLE)) {
						item.setTitle(child.getText());
						// System.out.println("TAG: title= " + child.getText());
					}
					if (child.getQualifiedName().equalsIgnoreCase(
							CConstant.TAG_CONTENT)) {
						// System.out.println("TAG: content= " +
						// child.getText());
						item.setContent(child.getText());
					}
					if (child.getQualifiedName().equalsIgnoreCase(
							CConstant.TAG_IMG)) {
						item.setImg(child.getText());
						// System.out.println("TAG: img= " + child.getText());
					}
				}
				if (item.getTitle() != null && item.getContent() != null
						&& !item.getContent().equals("")) {
					response.add(item);
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return response;
	}

	public static Document parse(InputStream input) throws DocumentException,
			ConnectException {
		SAXReader reader = new SAXReader();
		Document document = reader.read(input);
		return document;
	}
}
